package com.shockweb.service.ioc.impl.spring;

import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

 

/**
 * 获取ApplicationContext和Object的工具类
 * @author 彭明华
 * history:
 * 2017年6月9日 彭明华创建
 */
@Component
@SuppressWarnings({ "rawtypes", "unchecked" })
public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

 
    /**
     * 设置ApplicationContext
     */
    public void setApplicationContext(ApplicationContext arg0)throws BeansException {
        applicationContext = arg0;
    }

 

    /**
     * 获取applicationContext对象
     * @return
     */

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

     

    /**
     * 根据bean的id来查找对象
     * @param id
     * @return
     */
    public static <T> T getBeanById(String id){
        return (T)applicationContext.getBean(id);
    }

     

    /**
     * 根据bean的class来查找对象
     * @param c
     * @return
     */
    public static <T> T getBeanByClass(Class c){
        return (T)applicationContext.getBean(c);
    }

     

    /**
     * 根据bean的class来查找所有的对象(包括子类)
     * @param c
     * @return
     */
    public static Map getBeansByClass(Class c){
        return applicationContext.getBeansOfType(c);

    }

}
